import { TreeData, TreeNode } from 'element-ui/types/tree';
import store from '../../store';
import http from 'src/framework/network/http';

export async function loadNode(node: TreeNode<string, TreeData>, resolve: Function) {
    const id = node.data?.id
    const type = ['village', 'stages', 'building', 'unit', 'room'][node.level]
    const result = await queryTreeNodes({ id, type })
    resolve(result)
}

export async function queryTreeNodes(params: { id?: string, type: string }) {
    const orgId = store.getters.vid ?? ''
    const nodes = await http.post('/resource/info/tree', {
        orgId,
        ...params
    })
    // 根据name排序
    if(params.type != 'village'){
        nodes.sort((a,b)=>{
            const numa = parseFloat(a.name)
            const numb = parseFloat(b.name)
            if (isNaN(numa) || isNaN(numb)) {
                return a.name.localeCompare(b.name)
            }else {
                return numa - numb
            }
        })
    }

    const meansure = {
        village: '',
        stages: '期',
        building: '栋',
        unit: '单元',
        room: '室'
    }[params.type]

    nodes.forEach(d => {
        d.isLeaf = !d.childType
        d.name += meansure
        d.key = params.type + ':' + d.id
    })

    return nodes
}

export type Room = {
    address: string
    id: number
    unitName: string
    unitId: string
    buildingCode: string
    buildingId: string
    roomCode: string
    stagesName: string
    stagesId: string
    villageId: string
    villageName: string
}

export function queryRoom(params:{roomId: string}) {
    return http.get<Room>(`/resource/room/queryRoomByRoomId/${params.roomId}`)
}